<?php 
require_once('../includes/settings.php');
require_once('../includes/functions.php');
require_once('../includes/repository.php');
require_once('../includes/sql.php');
deny_get_request();
deny_anonymous();
parameters_check($_REQUEST['action']);

$words_exist=array();
$words_no_exist=array();
$words_were_collected=array();
$words_were_forgotten=array();

function collect_words($words,$user_id){
	global $SQL,$words_were_collected,$words_were_forgotten;
	$result=TRUE;
	$insert_user_word_stmt = Repository::prepare($SQL['user_words']['insert']);
	$update_user_word_stmt = Repository::prepare($SQL['user_words']['update']);
	foreach ($words as $word) {
		$word_id = Word::get_id($word);
		//已经收藏过的单词将熟悉程度重置为1	
		if(Word::is_collected($user_id,$word_id)){
			$result =UserWord::set_familiarity(1, $user_id, $word_id, $update_user_word_stmt);
			$words_were_forgotten[]=$word;
		}else{
			$result =UserWord::create($user_id, $word_id, $insert_user_word_stmt);
			$words_were_collected[]=$word;
		}
	}
	Repository::commit();
}

$user_id = user_val('id');
$action = strtolower($_REQUEST['action']);

if($action == 'collect_words'){
	$str=strtolower($_POST['words']);
	$words=array_unique(explode(",", $str ));
	foreach ($words as $word) {
		$word_id = Word::get_id($word);
		if($word_id>0){
			$words_exist[] = strip_quotes($word);
		}else{
			$words_no_exist[] = strip_quotes($word);
		}
	}
	collect_words($words_exist,$user_id);
	$result = array(
		"success"=>count($words_exist),
		"collected_words"=>$words_were_collected,
		"forgot_words"=>$words_were_forgotten,
		"failed"=>count($words_no_exist),
		"failed_words"=>$words_no_exist
	);
	_json(json_encode($result));

}elseif ($action=='remove') {
	UserWord::remove($user_id,intval($_POST['word_id']));
	Repository::commit();
	Repository::close();
	$_SESSION['removed_user_word']=$_POST['word'];
	header('location:'.$_SERVER['HTTP_REFERER']);

}elseif($action=="collect_word"){
	$id = UserWord::create($user_id,intval($_POST['word_id']));
	Repository::commit();
	_json(json_encode(array("success"=>true,"user_word_id"=>$id)));

}elseif ($action=="set_familiarity") {
	$familiarity=intval($_POST['familiarity']);
	$word_id = intval($_POST['word_id']);
	$result = UserWord::set_familiarity($familiarity, $user_id, $word_id);
	Repository::commit();
	Repository::close();
	_jsonp($result == 1);
}
?>